package com.dji.sample.manage.service.impl;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dji.sample.common.constant.CommonConstant;
import com.dji.sample.common.error.ServiceException;
import com.dji.sample.common.model.Pagination;
import com.dji.sample.common.model.PaginationData;
import com.dji.sample.manage.dao.FireCheckRecordMapper;
import com.dji.sample.manage.model.dto.DeviceDTO;
import com.dji.sample.manage.model.dto.FireCheckRecordAddDTO;
import com.dji.sample.manage.model.dto.FireCheckRecordQuery;
import com.dji.sample.manage.model.entity.FireCheckRecordEntity;
import com.dji.sample.manage.service.FireCheckRecordService;
import com.dji.sample.manage.service.IDeviceService;
import com.dji.sample.wayline.model.entity.WaylineFileEntity;
import com.dji.sample.wayline.service.IWaylineFileService;
import com.google.common.collect.ImmutableMap;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yjt
 * @since 2022-11-11
 */
@Service
public class FireCheckRecordServiceImpl extends ServiceImpl<FireCheckRecordMapper, FireCheckRecordEntity> implements FireCheckRecordService {

    @Autowired
    IWaylineFileService waylineFileService;

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    IDeviceService deviceService;

    @Override
    public void addFireCheckRecord(FireCheckRecordAddDTO fireCheckRecordAddDTO) {
        FireCheckRecordEntity fireCheckRecordEntity = new FireCheckRecordEntity();
        BeanUtils.copyProperties(fireCheckRecordAddDTO, fireCheckRecordEntity);
        fireCheckRecordEntity.setCreateTime(new Date());
        this.save(fireCheckRecordEntity);
    }

    @Override
    public PaginationData<FireCheckRecordEntity> page(FireCheckRecordQuery param) {
        if (param.getPage() == null || param.getPageSize() == null) {
            param.setPage(1L);
            param.setPageSize(10L);
        }
        LambdaQueryWrapper<FireCheckRecordEntity> lambdaQueryWrapper = new LambdaQueryWrapper<FireCheckRecordEntity>().eq(StringUtils.hasText(param.getDeviceSn()), FireCheckRecordEntity::getDeviceSn, param.getDeviceSn()).orderByDesc(FireCheckRecordEntity::getCreateTime);

        Page<FireCheckRecordEntity> pagination = this.page(new Page<>(param.getPage(), param.getPageSize()), lambdaQueryWrapper);


        if (!pagination.getRecords().isEmpty()) {
            List<Long> ids = pagination.getRecords().stream().map(FireCheckRecordEntity::getLineId).collect(Collectors.toList());
            List<WaylineFileEntity> list = waylineFileService.findByIds(ids);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            pagination.getRecords().forEach(page -> {
                String time = formatter.format(page.getCreateTime());
                page.setLineName(time + "日火情检测");
                if (page.getLineId() != null) {
                    Optional<WaylineFileEntity> optional = list.stream().filter(s -> s.getId() == page.getLineId().intValue()).findFirst();
                    optional.ifPresent(waylineFile -> page.setLineName(waylineFile.getName()));
                }
            });
        }
        return new PaginationData<>(pagination.getRecords(), new Pagination(pagination));
    }

    @Override
    public void enableFireCheck(String deviceSn) {
        // 轮询+推送模式
        Optional<DeviceDTO> optional = deviceService.getDeviceBySn(deviceSn);
        if (optional.isPresent()) {
            //TODO broker轮询 加上重启继续执行
         //   redisTemplate.opsForList().leftPush(CommonConstant.FIRE_CHECK, JSONObject.toJSONString(ImmutableMap.of("deviceSn", optional.get().getDeviceSn(), "orgCode", optional.get().getOrgCode(), "orgId", optional.get().getOrgId(), "deviceNo", optional.get().getDeviceNo())));
            redisTemplate.convertAndSend(CommonConstant.FIRE_CHECK_TOPIC, JSONObject.toJSONString(ImmutableMap.of("deviceSn", optional.get().getDeviceSn(), "orgCode", optional.get().getOrgCode(), "orgId", optional.get().getOrgId(), "deviceNo", optional.get().getDeviceNo())));
            return;
        }
        throw new ServiceException("设备不存在");

    }
}
